import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import {
  Form, Input, Button, Upload, message, Space, Typography, Row, Col,
} from 'antd';
import { useState } from 'react';
import { useHistory } from 'react-router-dom';

import * as APIS from '../../constants/api-constants';

const { Title } = Typography;
const { TextArea } = Input;

const formItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 14 },
};
const tailLayout = {
  wrapperCol: { offset: 3, span: 16 },
};

const handleBeforeUpload = (file: { type: string; size: number; }) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('只支持JPG/PNG格式的图片!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片必须小于2MB!');
  }
  return isJpgOrPng && isLt2M;
};

export default () => {
  const [form] = Form.useForm();
  const [imageFileName, setImgUrl] = useState('');
  const history = useHistory();
  const header = { authorization: localStorage.getItem('Authorization') ?? '' };

  const handleChange = (info: any) => {
    const { file } = info;
    if (file.status === 'done') {
      message.success(`${info.file.name} 上传成功`);
      setImgUrl(info.file.response.mainData.url);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败.`);
    }
  };

  const { run, loading } = useRequest((data) => {
    const {
      title, description, epilog, prefixion
    } = data;
    return {
      url: APIS.TEMPLATE,
      method: 'POST',
      data: {
        title,
        description,
        epilog,
        prefixion,
        logo: imageFileName
      }
    };
  }, {
    manual: true,
    onSuccess: () => {
      history.push('/home/success');
    },
    onError: (err) => {
      console.log(err);
    },
  });

  return (
    <>
      <Row>
        <Col span={6}>
          <Title level={2}>增加问卷</Title>
        </Col>
      </Row>
      <Form
        labelAlign="left"
        form={form}
        {...formItemLayout}
        name="control-hooks"
        onFinish={(data) => { run(data); }}
      >
        <Form.Item
          name="title"
          label="问卷标题"
          rules={[{
            required: true,
            message: '请输入问卷标题'
          }]}
        >
          <Input />
        </Form.Item>
        <Form.Item name="description" label="问卷描述">
          <TextArea
            placeholder="请输入问卷描述"
            autoSize={{ minRows: 3, maxRows: 5 }}
          />
        </Form.Item>
        <Form.Item name="epilog" label="问卷结语">
          <TextArea
            placeholder="请输入问卷结语"
            autoSize={{ minRows: 3, maxRows: 5 }}
          />
        </Form.Item>
        <Form.Item name="prefixion" label="问卷编号开头">
          <Input />
        </Form.Item>
        <Form.Item
          name="logo"
          label="问卷logo"
          rules={[{
            required: true,
            message: '请上传logo'
          }]}
        >
          <Upload
            name="avatar"
            headers={header}
            action={APIS.IMAGE}
            showUploadList={false}
            maxCount={1}
            listType="picture-card"
            beforeUpload={handleBeforeUpload}
            onChange={handleChange}
          >
            {imageFileName
              ? <img src={`${APIS.IMAGE}/?filename=${imageFileName}`} alt="avatar" style={{ width: '100%' }} />
              : (
                <div>
                  {loading ? <LoadingOutlined /> : <PlusOutlined />}
                  <div style={{ marginTop: 8 }}>logo上传</div>
                </div>
              )}
          </Upload>
        </Form.Item>
        <Form.Item {...tailLayout}>
          <Space>
            <Button type="primary" htmlType="submit" loading={loading}>
              保存
            </Button>
            <Button htmlType="button" onClick={() => { history.goBack(); }}>
              取消
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </>
  );
};
